package net.lainiao.mycost.controller;

import net.lainiao.mycost.utils.Page;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.RequestWrapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipInputStream;

/**
 * Created by Administrator on 2017/3/22.
 */
@Controller
@RequestMapping("/processdefin/")
public class ProcessDefinitonController extends Page {


    @Autowired
    private ProcessEngine engine;

    @RequestMapping("loadAdd.do")
    public String loadAdd() {
        return "processdefin/processdefin_add";
    }

    @RequestMapping("deployZip.do")
    public String deployZip(@RequestParam(value = "file", required = false) MultipartFile file, String name, Model model) {
        try {
            ZipInputStream zis = new ZipInputStream(file.getInputStream());
            DeploymentBuilder deploymentBuilder = engine.getRepositoryService().createDeployment();
            Deployment deployment = deploymentBuilder.name(name).addZipInputStream(zis).deploy();
            if (deployment != null && deployment.getId() != null) {
                model.addAttribute("info", "[" + name + "]流程部署成功");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "processdefin/processdefin_add";
    }

    @RequestMapping("list.do")
    public String list(Model model){
        List<ProcessDefinition> list=engine.getRepositoryService().createProcessDefinitionQuery().orderByProcessDefinitionVersion().asc().list();
        Map<String,ProcessDefinition> map=new HashMap<>();
        if(list!=null&&list.size()>0){
            for(ProcessDefinition processDefinition:list){
                map.put(processDefinition.getKey(),processDefinition);
            }
        }
        list=new ArrayList<>();
        for(ProcessDefinition processDefinition:map.values()){
            list.add(processDefinition);
        }
        model.addAttribute("list",list);
        return "processdefin/processdefin_list";
    }


}
